package com.tsingteng.cosfun.ui.found;


import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dingmouren.layoutmanagergroup.viewpager.OnViewPagerListener;
import com.dingmouren.layoutmanagergroup.viewpager.ViewPagerLayoutManager;
import com.pili.pldroid.player.IMediaController;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BasePresenterFragment;
import com.tsingteng.cosfun.bean.AttentRecommendbean;
import com.tsingteng.cosfun.bean.BlindResp;
import com.tsingteng.cosfun.bean.EventBean;
import com.tsingteng.cosfun.bean.FollowBean;
import com.tsingteng.cosfun.bean.FoundAtBean;
import com.tsingteng.cosfun.bean.HomeBean;
import com.tsingteng.cosfun.bean.JoinCostarBean;
import com.tsingteng.cosfun.bean.OpusBean;
import com.tsingteng.cosfun.bean.RecommenResp;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.cosfun.adapter.OpusAdapterNew;
import com.tsingteng.cosfun.ui.cosfun.contract.OpusContract;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverListener;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverManager;
import com.tsingteng.cosfun.ui.cosfun.presenter.OpusPresenter;
import com.tsingteng.cosfun.ui.found.adapter.FoundVideoListAdapter;
import com.tsingteng.cosfun.ui.message.MessageFragment;
import com.tsingteng.cosfun.ui.mine.TerminalActivity;
import com.tsingteng.cosfun.ui.setting.MobileBindFragment;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.NetUtils;
import com.tsingteng.cosfun.widget.MyRecycleView;
import com.tsingteng.cosfun.widget.dialog.BlindPhoneDialog;
import com.tsingteng.cosfun.widget.dialog.ProgressDialog;
import com.tsingteng.cosfun.widget.dialog.ShowNetStatusDialog;
import com.tsingteng.cosfun.widget.view.MySwipeRefreshLayout;

import org.simple.eventbus.EventBus;

import java.util.List;
import java.util.Objects;



/**
 * 活动视频fragment
 * author :zht
 */
public class FoundVideoPlayFragment extends BasePresenterFragment<OpusPresenter, OpusContract.IOpusView> implements OpusContract.IOpusView, View.OnClickListener
        , FoundVideoListAdapter.OnItemClickLisenter
        , ShowNetStatusDialog.OnItemClickListener
        , ObserverListener
        ,FoundVideoListAdapter.OnCanClickListener
        ,FoundJoinActivity.OnFragmentTriggerResult
        ,BlindPhoneDialog.BindPhoneListener {

    private MySwipeRefreshLayout mFragmentFoundRefresh;
    private ProgressBar mProgressBar;
    private ProgressBar mVProgressBar;
    private List<OpusBean> mListVideo;
    private ShowNetStatusDialog.Builder netBuilder;
    private ShowNetStatusDialog netStatusDialog = null;
    private int currentPosition = 0;
    private ViewPagerLayoutManager mLayoutManager;
    private FoundVideoListAdapter mFoundAdapter;
    private IMediaController.MediaPlayerControl mPlayer;
    private static final int SHOW_PROGRESS = 2;
    private long pageType = 0;
    private AudioManager audio = null;
    private boolean canPlay = false;
    private boolean isCanClickJoin = true;//是否可以点击合拍按钮
    private ProgressDialog progressDialog;
    private OpusBean mOpusBean;
    protected FoundVideoListAdapter.FooterState mState = FoundVideoListAdapter.FooterState.Normal;

    public void setDataStype(List<OpusBean> listVideo, int currentPosition) {
        this.mListVideo = listVideo;
        this.pageType = System.currentTimeMillis();
        this.currentPosition = currentPosition;
    }

    @Override
    protected void initData(View rootView) {
        mFragmentFoundRefresh = rootView.findViewById(R.id.fragment_found_refresh);
        RecyclerView mFoundList = rootView.findViewById(R.id.found_list);
        mProgressBar = rootView.findViewById(R.id.play_progress_bar);
        mVProgressBar = rootView.findViewById(R.id.volume_progress_bar);
        ImageView mFoundPlayBack = rootView.findViewById(R.id.found_play_back);
        netBuilder = new ShowNetStatusDialog.Builder(getActivity(), getActivity());
        //这只下载进度框
        progressDialog = new ProgressDialog(getActivity());
        mFoundPlayBack.setVisibility(View.VISIBLE);
        mFoundPlayBack.setOnClickListener(this);
        mLayoutManager = new ViewPagerLayoutManager(getActivity(), OrientationHelper.VERTICAL);
        mFoundAdapter = new FoundVideoListAdapter(getActivity(), pageType, mListVideo, this,this);
        mFoundList.setAdapter(mFoundAdapter);
        mFoundList.setLayoutManager(mLayoutManager);
        mFragmentFoundRefresh.setOnRefreshListener(() -> mFragmentFoundRefresh.setRefreshing(false));
        ObserverManager.getInstance().add(this);
        audio = (AudioManager) getActivity().getSystemService(Service.AUDIO_SERVICE);
        setState(FoundVideoListAdapter.FooterState.Normal);
        initListener();
        if (currentPosition > 0 && currentPosition < mListVideo.size()) {
            mLayoutManager.scrollToPositionWithOffset(currentPosition, 0);
            mLayoutManager.setStackFromEnd(true);
        }
        if (!NetUtils.isNetworkAvailable()) {
            showNetType(1, "网络连接错误", "刷新 ");
            return;
        }
        play();
    }

    void initListener() {
        mLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {


            @Override
            public void onPageRelease(boolean isNext, int position) {
                playerPause(position);
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                currentPosition = position;
                mProgressBar.setProgress(0);
                play();
                if (0 == mListVideo.size()) {
                    return;
                }

            }

            @Override
            public void onLayoutComplete() {
            }

        });
    }

    protected void setState(FoundVideoListAdapter.FooterState mState) {
        this.mState = mState;
        if (null ==getActivity()){
            return;
        }
        (getActivity()).runOnUiThread(() -> changeAdaperState());
    }

    //改变底部bottom的样式
    protected void changeAdaperState() {
        if (mFoundAdapter != null && mFoundAdapter.mFooterHolder != null) {
            mFoundAdapter.mFooterHolder.setStatus(mState);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        playerPause(currentPosition);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        playerPause(currentPosition);
        if (mFoundAdapter != null) {
            mFoundAdapter.clearPlayer();
        }
    }

    //播放暂停
    public void playerPause(int position) {
        if (mFoundAdapter != null) {
            mFoundAdapter.stopPlay(position);
            return;
        }
        EventBean eventBean = new EventBean();
        eventBean.setType(pageType);
        EventBus.getDefault().post(eventBean, FoundVideoListAdapter.EVENT_PAUSE);
    }

    @Override
    protected OpusPresenter createPresenter() {
        return new OpusPresenter();
    }

    @Override
    protected View initHeader() {
        return null;
    }

    @Override
    protected MyRecycleView createRecycleView() {
        return null;
    }

    @Override
    protected BaseQuickAdapter createAdapter() {
        return null;
    }

    @Override
    protected void refresh() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.found_play_back:
                Objects.requireNonNull(getActivity()).finish();
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onLoadMoreRequested() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_found_play_video;
    }

    @Override
    public void showLogonResult(HomeBean.DataBean dataBean) {

    }

    @Override
    public void showSendResult(int type) {

    }

    @Override
    public void showCostarVideoResult(JoinCostarBean joinCostarBean) {
        if (!isCanClickJoin) return;
        isCanClickJoin = false;
        VideoHelper.getIntence().downVideo(getContext(), mOpusBean.getIsActivity(),joinCostarBean, new VideoHelper.OnVideoHelperDowmVideoListener() {
            @Override
            public void onStartDown() {
                if (progressDialog == null) progressDialog = new ProgressDialog(getActivity());
                progressDialog.show();
                isCanClickJoin = true;
            }

            @Override
            public void onPregress(int pregress) {
                progressDialog.setmProgressbar(pregress);
            }

            @Override
            public void onComplete() {
                progressDialog.disMissDialog();
                if (null ==getActivity()){
                    return;
                }
                VideoHelper.getIntence().setmOpusBean(mOpusBean);
                if ("1".equals(mOpusBean.getIsActivity())) {
                    VideoHelper.getIntence().setActivityId(mOpusBean.getActivityId());
                    Navigate.gotoCostar(getActivity(), mOpusBean.getActivityId());
                }else{
                    VideoHelper.getIntence().setActivityId(-1);
                    Navigate.gotoCostar(getActivity(), -1);
                }
                isCanClickJoin = true;
            }
        });
    }
    @Override
    public void getFollowResult(FollowBean followBean) {

    }

    @Override
    public void shoWorkData(HomeBean.DataBean data) {

    }

    @Override
    public void showFound(FoundAtBean data) {

    }

    @Override
    public void showVideoInfo(OpusBean opusBean) {

    }

    @Override
    public void showFocusInfo(RecommenResp attentRecommendbeans) {

    }

    @Override
    public void showNoFollowResult(FollowBean followBean, int position) {

    }


    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            long pos;
            switch (msg.what) {
                case SHOW_PROGRESS:
                    if (mPlayer == null || !mPlayer.isPlaying()) {
                        return;
                    }
                    pos = setProgress();
                    mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
                    break;
                case 100:
                    if (mVProgressBar != null && mVProgressBar.getVisibility() == View.VISIBLE) {
                        mVProgressBar.setVisibility(View.INVISIBLE);
                    }
                    break;
                case 10000:
                    play();
                    break;
                case 10001:
                    if (mFoundAdapter != null) {
                        mFoundAdapter.startPlay(currentPosition);
                    }
            }
        }
    };

    private long setProgress() {
        if (mPlayer == null) {
            return 0;
        }

        long position = mPlayer.getCurrentPosition();
        long duration = mPlayer.getDuration();
        if (mProgressBar != null) {
            if (duration > 0) {
                mProgressBar.setProgress((int) position);
                mProgressBar.setMax((int) duration);
            }
        }
        return position;
    }

    public void play() {
        if (!canPlay && !NetUtils.isWiFi()) {
            showNetType(0, "非wifi环境不播放视频", "还是想看");
            playerPause(currentPosition);
            return;
        }
        if (mListVideo == null || 0 == mListVideo.size()) {
            return;
        }
        ObserverManager.getInstance().notifyObserver(ObserverListener.EVENT_CHANGE_OPUS, currentPosition, mListVideo.get(currentPosition).getProfileId());

        if (mFoundAdapter != null) {
            mHandler.removeMessages(10001);
            mHandler.sendEmptyMessageDelayed(10001, 200);
            return;
        }
        EventBean eventBean = new EventBean();
        eventBean.setPosition(currentPosition);
        eventBean.setType(pageType);
        EventBus.getDefault().post(eventBean, OpusAdapterNew.EVENT_START);
    }

    private void showNetType(int type, String des, String nextStr) {
        if (null == netBuilder) {
            return;
        }
        netStatusDialog = netBuilder.setMessage(type, des, nextStr).setItemClickListener(this).createDialog();
        netStatusDialog.show();
    }

    @Override
    public void showPlayProgress(int position, IMediaController.MediaPlayerControl mediaPlayerControl) {
        mPlayer = mediaPlayerControl;
        mHandler.removeMessages(SHOW_PROGRESS);
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
    }

    @Override
    public void observerUpData(int eventType, int index, int id) {
        switch (eventType) {
            case ObserverListener.KEYCODE_VOLUME_UP://音量加
                int max_volume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                int cu_volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                mVProgressBar.setVisibility(View.VISIBLE);
                mVProgressBar.setMax(max_volume);
                mVProgressBar.setProgress(cu_volume);
                mHandler.removeMessages(100);
                mHandler.sendEmptyMessageDelayed(100, 3000);
                break;
            case ObserverListener.KEYCODE_VOLUME_DOWN://音量减
                max_volume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                cu_volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                mVProgressBar.setVisibility(View.VISIBLE);
                mVProgressBar.setMax(max_volume);
                mVProgressBar.setProgress(cu_volume);
                mHandler.removeMessages(100);
                mHandler.sendEmptyMessageDelayed(100, 3000);
                break;
        }
    }

    @Override
    public void onPlay() {
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
        canPlay = true;
        play();
    }

    @Override
    public void onRefreshPlay() {
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
        play();
    }

    @Override
    public void onNetRefresh() {
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
    }

    @Override
    public void showCanClick(OpusBean opusBean) {
        if (null == opusBean){
            return;
        }
        mOpusBean =opusBean;
        if (LogonUtils.chckLogon(getActivity(),false,3)){
//            mPresenter.getJoin(mOpusBean.getId());
            if ("1".equals(mOpusBean.getIsActivity())) {
                mPresenter.getBlindPhone();
            }else {
                mPresenter.getCostarVideoInfo(String.valueOf(mOpusBean.getId()));
            }
        }
    }
    @Override
    public void showState(BlindResp resp) {
         if ("success".equals(resp.getState())){
            mPresenter.getCostarVideoInfo(String.valueOf(mOpusBean.getId()));
         }else{
             BlindPhoneDialog mPhoneDialog = new BlindPhoneDialog(getActivity(),this);
             mPhoneDialog.show();
         }
    }

    @Override
    public void showJoinAdd(BlindResp resp) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
    }

    @Override
    public void onFragmentTriggerResult(int requestCode, int resultCode, Intent data) {
        if (null ==getActivity()){
            return;
        }
        if (Constant.REQUESTCODE ==requestCode) {
            getActivity().finish();
        }
    }

    @Override
    public void onBindPhoneListener(String type) {
        switch (type){
            case Constant.BLINDGO:
                TerminalActivity.showFragment(getActivity(), MobileBindFragment.class, null);
                break;
            case Constant.PASSOFF:
                mPresenter.getCostarVideoInfo(String.valueOf(mOpusBean.getId()));
                break;
        }
    }
    @Override
    public void showCheckAndRemmend() {

    }
}
